/// 使用 File api

/// 使用 Uint8List 数据类型
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:dio/dio.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
/// 授权管理
import 'package:permission_handler/permission_handler.dart';

/// 保存文件或图片到本地
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:flutter/material.dart';
//国际化
import 'package:flutter_app/generated/l10n.dart';
class AppUtil {
  /// 默认为下载网络图片，如需下载资源图片，需要指定 [isAsset] 为 `true`。
  static Future<Uint8List> imgUrlToUint8List(String imageUrl,
      {bool isAsset: false}) async {
    try {
      if (imageUrl == null) throw '保存失败，图片不存在！';

      /// 保存的图片数据
      Uint8List imageBytes;

      if (isAsset == true) {
        /// 保存资源图片
        ByteData bytes = await rootBundle.load(imageUrl);
        imageBytes = bytes.buffer.asUint8List();
      } else {
        /// 保存网络图片
        var response = await Dio()
            .get(imageUrl, options: Options(responseType: ResponseType.bytes));
        imageBytes = Uint8List.fromList(response.data);
        // CachedNetworkImage image = CachedNetworkImage(imageUrl: imageUrl);
        // DefaultCacheManager manager =
        //     image.cacheManager ?? DefaultCacheManager();
        // Map<String, String> headers = image.httpHeaders;
        // File file = await manager.getSingleFile(
        //   image.imageUrl,
        //   headers: headers,
        // );
        // imageBytes = await file.readAsBytes();
      }
      return imageBytes;
    } catch (e) {
      print(e.toString());
    }
    return null;
  }

  /// 保存图片到相册
  static Future<void> saveImage(Uint8List imageBytes) async {
    try {
      if (imageBytes.length <= 0) {
        Fluttertoast.showToast(
            msg: '保存失败，图片不存在！', gravity: ToastGravity.CENTER);
      }

      /// 权限检测
      PermissionStatus storageStatus = await Permission.storage.status;
      if (storageStatus != PermissionStatus.granted) {
        storageStatus = await Permission.storage.request();
        if (storageStatus != PermissionStatus.granted) {
          Fluttertoast.showToast(
              msg: '无法存储图片，请先授权！', gravity: ToastGravity.CENTER);
        }
      }

      /// 保存图片
      final result = await ImageGallerySaver.saveImage(imageBytes);

      if (result == null || result == '') {
        Fluttertoast.showToast(msg: '图片保存失败', gravity: ToastGravity.CENTER);
      }
      Fluttertoast.showToast(msg: '图片保存成功', gravity: ToastGravity.CENTER);
    } catch (e) {
      print(e.toString());
    }
  }

  /// 截屏图片生成图片流Uint8List
  static Future<Uint8List> capturePngToUint8List(GlobalKey repaintWidgetKey) async {

    try {
      RenderRepaintBoundary boundary =
          repaintWidgetKey.currentContext.findRenderObject();
      double dpr = ui.window.devicePixelRatio; // 获取当前设备的像素比
      ui.Image image = await boundary.toImage(pixelRatio: dpr);
      ByteData _byteData =
          await image.toByteData(format: ui.ImageByteFormat.png);
      Uint8List pngBytes = _byteData.buffer.asUint8List();
      return pngBytes;
    } catch (e) {
      print(e);
    }
    return null;
  }
  /// 复制
  static void copy(String content,{String successMsg}){
    ClipboardData data = new ClipboardData(text:content);
    Clipboard.setData(data);
    Fluttertoast.showToast(msg:successMsg ?? '复制成功', gravity: ToastGravity.CENTER);
  }
  /// dialog
  static void showSimpleDialog(context,{List<Widget> children}){
    showDialog(
        context: context,
        builder: (ctx) {
          return SimpleDialog(
            // title: Text("SimpleDialog"),
            titlePadding: EdgeInsets.all(10),
            backgroundColor: Colors.white,
            elevation: 5,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(6))),
            children: children
          );
        });
  }
  ///数字格式化
  static String formatNum(num, {point: 0}) {
    if (num != null) {
      String str = double.parse(num.toString()).toString();
      // 分开截取
      List<String> sub = str.split('.');
      // 处理值
      List val = List.from(sub[0].split(''));
      // 处理点
      List<String> points = List.from(sub[1].split(''));
      //处理分割符
      for (int index = 0, i = val.length - 1; i >= 0; index++, i--) {
        // 除以三没有余数、不等于零并且不等于1 就加个逗号
        if (index % 3 == 0 && index != 0 ) val[i] = val[i] + ',';
      }
      // 处理小数点
      for (int i = 0; i <= point - points.length; i++) {
        points.add('0');
      }
      //如果大于长度就截取
      if (points.length > point) {
        // 截取数组
        points = points.sublist(0, point);
      }
      // 判断是否有长度
      if (points.length > 0) {
        return '${val.join('')}.${points.join('')}';
      } else {
        return val.join('');
      }
    } else {
      return "0.0";
    }
  }
}
